import redis
import time

from use_redis.settings import HOST,  PWD, PORT, DB


def connect_redis():
    global db_cn
    host = HOST
    pwd = PWD
    port = PORT
    db = DB
    try:
        db_cn = redis.Redis(host=host, port=port, db=db, decode_responses=True, password=pwd)
    except Exception as e:
        print(e)
    return db_cn


def get_task():
    """取任务"""
    COMPANY_NAME = 'WeiJianWei'
    while True:
        redis_db = connect_redis()
        pipe = redis_db.pipeline()
        # 自己的储存名称
        pipe.spop(COMPANY_NAME)
        task = pipe.execute()[0]
        if not task:
            print('task finish!')
        # 采集运行函数，通过返回值判断该任务是否成功，不成功则重新扔回任务队列
        a = True
        print(task)

        if a:
            continue
        else:
            redis_db = connect_redis()
            pipe = redis_db.pipeline()
            pipe.sadd(COMPANY_NAME, task)
            pipe.execute()


def get_redis_size():
    COMPANY_NAME = 'WeiJianWei'
    redis_db = connect_redis()
    count = redis_db.scard(COMPANY_NAME)
    print('redis db 15 has {} jobs left'.format(count))


if __name__ == '__main__':
    get_redis_size()
